package com.yjz.ui.tab.bottom;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ScrollView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.yjz.ui.R;
import com.yjz.ui.tab.common.ITabLayout;
import com.yjz.ui.tab.common.TabInfo;
import com.yjz.ui.util.DisplayUtil;
import com.yjz.ui.util.ViewUtil;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 作用 : 底部的Tab容器
 * * 1. 透明度和底部透出，列表可渲染高度问题
 * * 2. 中间高度超过，凸起布局
 * 作者 : yjz
 * 时间 : 2024/9/18 15:23
 */
public class TabBottomLayout extends FrameLayout implements ITabLayout<TabBottomView, TabInfo<?>> {

    private static final String TAG_TAB_BOTTOM = "TAG_TAB_BOTTOM";

    private List<OnTabSelectedListener<TabInfo<?>>> tabSelectedChangeListeners = new ArrayList<>();
    private TabInfo<?> selectedInfo;
    private float bottomAlpha = 1f;
    // TabBottom高度
    private static float tabBottomHeight = 50;
    // TabBottom的头部线条高度
    private float bottomLineHeight = 0.5f;
    // TabBottom的头部线条颜色
    private String bottomLineColor = "#dfe0e1";
    private List<TabInfo<?>> infoList;

    public TabBottomLayout(@NonNull Context context) {
        this(context, null);
    }

    public TabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TabBottomLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public TabBottomView findTab(@NonNull TabInfo<?> data) {
        ViewGroup viewGroup = findViewWithTag(TAG_TAB_BOTTOM);
        int childCount = viewGroup.getChildCount();
        for (int i = 0; i < childCount; i++) {
            View view = viewGroup.getChildAt(i);
            if (view instanceof TabBottomView) {
                TabBottomView tabBottomView = (TabBottomView) view;
                if (data == tabBottomView.getTabInfo()) {
                    return tabBottomView;
                }
            }
        }
        return null;
    }

    @Override
    public void addTabSelectChangeListener(OnTabSelectedListener<TabInfo<?>> listener) {
        this.tabSelectedChangeListeners.add(listener);
    }

    @Override
    public void defaultSelected(@NonNull TabInfo<?> defaultInfo) {
        onSelected(defaultInfo);
    }

    private void onSelected(@NonNull TabInfo<?> nextInfo) {
        for (OnTabSelectedListener<TabInfo<?>> listener : tabSelectedChangeListeners) {
            listener.onTabSelectedChange(infoList.indexOf(nextInfo), selectedInfo, nextInfo);
        }
        this.selectedInfo = nextInfo;
    }

    @Override
    public void inflateInfo(@NonNull List<TabInfo<?>> infoList) {
        if (infoList.isEmpty()) return;
        this.infoList = infoList;
        // 清除之前的view
        for (int i = getChildCount() - 1; i > 0; i--) {
            removeViewAt(i);
        }
        selectedInfo = null;
        addBackground();

        // 清除之前的TabBottom listener.
        Iterator<OnTabSelectedListener<TabInfo<?>>> iterator = tabSelectedChangeListeners.iterator();
        while (iterator.hasNext()) {
            if (iterator.next() instanceof TabBottomView) {
                iterator.remove();
            }
        }
        int height = DisplayUtil.dp2px(tabBottomHeight, getResources());
        FrameLayout ll = new FrameLayout(getContext());
        int tabWidth = DisplayUtil.getDisplayWidthInPx(getContext()) / infoList.size();
        // 用于查找
        ll.setTag(TAG_TAB_BOTTOM);
        for (int i = 0; i < infoList.size(); i++) {
            TabInfo<?> info = infoList.get(i);
            LayoutParams layoutParams = new LayoutParams(tabWidth, height);
            layoutParams.gravity = Gravity.BOTTOM;
            // Tips：为何不用LinearLayout：当动态改变child大小后Gravity.BOTTOM会失效
            // 因为是frameLayout,每个都需要加上一个左边距
            layoutParams.leftMargin = i * tabWidth;
            // 创建tab
            TabBottomView tabBottomView = new TabBottomView(getContext());
            tabBottomView.setTabDataInfo(info);
            tabSelectedChangeListeners.add(tabBottomView);
            ll.addView(tabBottomView, layoutParams);
            tabBottomView.setOnClickListener(view -> onSelect(info));
        }
        // 添加分割线
        LayoutParams flPrams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        flPrams.gravity = Gravity.BOTTOM;
        addBottomLine();
        addView(ll, flPrams);
        // 修复底部凸出是造成内容的显示不全
        fixContentView();
    }

    /**
     * tab 选中
     */
    private void onSelect(TabInfo<?> info) {
        for (OnTabSelectedListener<TabInfo<?>> tabSelectedChangeListener : tabSelectedChangeListeners) {
            tabSelectedChangeListener.onTabSelectedChange(infoList.indexOf(info), selectedInfo, info);
        }
        this.selectedInfo = info;
    }

    /**
     * 添加底部的分割线
     */
    private void addBottomLine() {
        View bottomLine = new View(getContext());
        bottomLine.setBackgroundColor(Color.parseColor(bottomLineColor));

        LayoutParams bottomLineParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dp2px(bottomLineHeight, getResources()));
        bottomLineParams.gravity = Gravity.BOTTOM;
        bottomLineParams.bottomMargin = DisplayUtil.dp2px(tabBottomHeight - bottomLineHeight, getResources());
        addView(bottomLine, bottomLineParams);
        bottomLine.setAlpha(bottomAlpha);
    }

    /**
     * 添加底部tab的背景
     */
    private void addBackground() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.tab_bottom_layout_bg, null);
        LayoutParams layoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dp2px(tabBottomHeight, getResources()));
        layoutParams.gravity = Gravity.BOTTOM;
        addView(view, layoutParams);
        view.setAlpha(bottomAlpha);
    }

    /**
     * 设置底部tab的透明度
     *
     * @param bottomAlpha
     */
    public void setTabAlpha(float bottomAlpha) {
        this.bottomAlpha = bottomAlpha;
    }

    /**
     * 修复view显示不全的问题
     */
    private void fixContentView() {
        if (!(getChildAt(0) instanceof ViewGroup)) {
            return;
        }

        ViewGroup rootView = (ViewGroup) getChildAt(0);
        ViewGroup targetView = ViewUtil.findTypeView(rootView, RecyclerView.class);
        if (targetView == null) {
            targetView = ViewUtil.findTypeView(rootView, ScrollView.class);
        }
        if (targetView == null) {
            targetView = ViewUtil.findTypeView(rootView, AbsListView.class);
        }
        if (targetView != null) {
            clipBottomPadding(targetView);
        }
    }

    /**
     * 给ViewGrout设置底部的padding
     *
     * @param targetView TabBottomLayout下的第一个ViewGroup
     */
    public static void clipBottomPadding(ViewGroup targetView) {
        if (targetView != null) {
            targetView.setPadding(0, 0, 0, DisplayUtil.dp2px(tabBottomHeight, Resources.getSystem()));
            targetView.setClipToPadding(false);
        }
    }
}
